import { getRequest } from '@/utils/api';
import Vue from 'vue';
import Vuex from 'vuex'
import SockJS from 'sockjs-client';
import Stomp from 'stompjs'
import { Notification } from 'element-ui';

const now = new Date();

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        admins: [],
        loginAdmin: JSON.parse(window.sessionStorage.getItem('admin')),
        currentSessionAdmin: null,
        filterKey: '',
        stomp: null,
        isDot: {}
    },
    mutations: {
        initRoutes(state, data) {
            state.routes = data
        },
        initCurrentAdmin(state, data) {
            state.loginAdmin = data
        },
        changeCurrentSession(state, currentSessionAdmin) {
            state.currentSessionAdmin = currentSessionAdmin;
            Vue.set(state.isDot, state.loginAdmin.username + "#" + state.currentSessionAdmin.username, false)

        },
        addMessage(state, msg) {
            let mss = state.sessions[state.loginAdmin.username + '#' + msg.to];

            if (!mss) {
                Vue.set(state.sessions, state.loginAdmin.username + '#' + msg.to, [])
            }
            state.sessions[state.loginAdmin.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                //是否是自己发的消息，msg.notSelt是发给别的人消息，取反即为自己发生的消息
                self: !msg.notSelt
            })
        },
        INIT_DATA(state) {
            //浏览器本地的历史聊天记录
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state, data) {
            state.admins = data
        },

    },
    actions: {
        connect(context) {
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'))
            let token = window.sessionStorage.getItem('tokenStr')
            context.state.stomp.connect({ 'Auth-Token': token }, success => {
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    let msgObj = JSON.parse(msg.body)

                    if (!context.state.currentSessionAdmin || msgObj.from != context.state.currentSessionAdmin.username) {
                        Notification.info({
                            title: `【${msgObj.fromNickName}】发来一条消息`,
                            message: msgObj.content.length > 10 ? msgObj.content.substring(0, 10) : msgObj.content,
                            position: 'bottom-right'
                        })

                        Vue.set(context.state.isDot, context.state.loginAdmin.username + "#" + msgObj.from, true)
                    }

                    msgObj.notSelt = true
                    msgObj.to = msgObj.from
                    context.commit('addMessage', msgObj)
                })
            }, error => {
            })
        },

        initData(context) {
            context.commit('INIT_DATA')
            getRequest('/chat/admin').then(resp => {
                if (resp) {
                    context.commit('INIT_ADMINS', resp)
                }
            })

        },

    },
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;